<?php
namespace app\api\service\uniapp\mine;

use app\api\controller\uniapp\User;
use app\api\model\Region;
use app\api\model\ShopPayOrder;
use app\api\model\ShopYiwu;
use app\api\model\UserFinance;
use app\api\model\Users;
use app\api\model\UserSettle;
use app\api\model\UserStore;
use app\common\controller\Api;
use app\api\controller\Leshua;
use think\Db;

class Mine10 extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $userVo = ['user_id','head_pic','nickname','is_vip','vip_level','reg_time','level_text'];

    /**
     * 加载我的页面
     * @throws \think\Exception
     */
    public function load_mine(){
        //接收参数
        $user = session('authuser');
        //处理用户头像
        if (strpos($user['head_pic'], "https://thirdwx.qlogo.cn")=== false) {
            $img = str_replace('/public','',$user['head_pic']);
            if($img){
                $user['head_pic'] = config('img_url').$img;
            }
        }

        $user['ywq'] = number_format($user['ywq'],2);
        $user['jindou'] = number_format($user['jindou'],2);
        //易物订单
        $user['yiwu_order_sum'] = ShopPayOrder::where(['user_id'=>$user['user_id'],'status'=>1,'order_type'=>7])->count();
        //扫码订单
        $user['scan_order_sum'] = ShopPayOrder::where(['user_id'=>$user['user_id'],'status'=>1,'order_type'=>6])->count();
        //是否为商家
        $shop = UserStore::where('user_id','in',[$user['user_id'],$user['shop_account_id']])->find();
        $user['is_shop'] = $shop?true:false;
        //是否为分公司
        $user['is_daili'] = ($user['is_daili']>0||$user['daili_account_id']>0)?true:false;
        $this->success('加载成功',$user);
    }

    /**
     * 加载我的工作台数据
     * @throws \think\Exception
     */
    public function load_work(){
        $user = session('authuser');
        //接收参数
        $page = $this->request->param('page',1);
        $size = $this->request->param('size',20);
        $page = ($page-1)*$size;
        $type = $this->request->param('type',1);
        //获取直推会员数量
        $user['first'] = Users::where('first_leader',$user['user_id'])->count();
        //当天预估收入
        $todaytime = $this->getLeShuaTodayTime($user['user_id']);
        //halt($todaytime);
        $today_money = UserFinance::where(['user_id'=>$user['user_id'],'money_type'=>1,'create_time'=>array('>=',$todaytime)])->sum('money');
        //总收入
        $total_money = UserFinance::where(['user_id'=>$user['user_id'],'money_type'=>1])->sum('money');
        $user['today_money'] = str_format_two($today_money);
        $user['total_money'] = str_format_two($total_money);
        $user['all_team_money'] = str_format_two($user['all_team_money']);
        //halt($user);
        //获取会员团队
        if($type==1){
            $list = $this->loadvip($user['user_id'],$page,$size);
        }
        //获取收入
        if($type==2){
            $list = $this->load_income($user['user_id'],$page,$size);
        }
        if($type == 3){
            $list = $this->load_income_all($user['user_id'],$page,$size);
        }
        //获取业绩
        if($type == 4){
            $list = $this->load_achievement($user['user_id'],$page,$size);
        }
        $data['user'] = $user;
        $data['list'] = $list;
        $this->success('加载成功',$data);
    }

    /**
     * 获取直推人员列表
     * @param $user_id 推荐人ID
     * @param int $page
     * @param int $size
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function loadvip($user_id,$page=0,$size=20){
        $users = Users::where('first_leader',$user_id)->order('user_id desc')->limit($page,$size)->select();
        foreach ($users as $row){
            $row->visible($this->userVo);
        }
        return $users;
    }

    /**
     * 获取用户当前预估收益列表
     * @param $user_id
     * @param int $page
     * @param int $size
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function load_income($user_id,$page=0,$size=20){
        $todaytime = $this->getLeShuaTodayTime($user_id);
        $list = UserFinance::where(['user_id'=>$user_id,'money_type'=>1,'create_time'=>array('>=',$todaytime)])->limit($page,$size)->order('create_time desc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['create_time'] = date("Y-m-d H:i:s",$v['create_time']);
        }
        return $list;
    }

    /**
     * 获取用户所有收益列表
     * @param $user_id
     * @param int $page
     * @param int $size
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function load_income_all($user_id,$page=0,$size=20){
        $list = UserFinance::where(['user_id'=>$user_id,'money_type'=>1])->limit($page,$size)->order('create_time desc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['create_time'] = date("Y-m-d H:i:s",$v['create_time']);
        }
        return $list;
    }

    /**
     * 获取用户在乐刷最后的打款时间
     * @param $user_id
     * @return false|int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLeShuaTodayTime($user_id){
        //获取用户当天乐刷打款时间,当天有打款的，按当天打款记录，无打款记录则向乐刷查询当天打款记录。如果乐刷也无当天打款记录，则查用户上一个打款记录，还是没有的则表示用户无打款记录。
        $today = date("Y-m-d");
        $usersettle = UserSettle::where(['user_id'=>$user_id,'settleDate'=>$today])->find();
        if($usersettle){
            $todaytime = $usersettle['bankretTime'];
        }else{
            $leshua = new Leshua();
            $settle = $leshua->settle_query($user_id);
            //halt($settle);
            if($settle['status']){
                $todaytime = $settle['data'];
            }else{
                //查询上一个打款记录
                $usersettle = UserSettle::where(['user_id'=>$user_id])->order('id desc')->find();
                if($usersettle){
                    $todaytime = empty($usersettle['settleData'])?strtotime("2000-01-01"):$usersettle['settleData'];
                }else{
                    //如果没有任何打款记录，表示用户没有得过现金，时间是多少就无所谓了。
                    $todaytime = strtotime("2000-01-01");
                }
            }
        }
        return $todaytime;
    }

    /**
     * 获取用户总业绩列表
     * @param $user_id
     * @param int $page
     * @param int $size
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function load_achievement($user_id,$page=0,$size=20){
        //获取下级所有客户
        $userList = [$user_id];
        get_lower_user($user_id,$userList);
        //halt($userList);
        $list = ShopPayOrder::where('user_id','in',$userList)->where("status",'in',[1,3])->where('money_type','in',[1,2,6])->limit($page,$size)->order('create_time desc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['remark'] = "购买商品";
            $list[$k]['create_time'] = $v['create_time_text'];//date("Y-m-d H:i:s",$v['create_time']);
            $list[$k]['money'] = $v['order_money'];
        }
        return $list;
    }

    /**
     * 加载分公司数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function load_office(){
        $user = session('authuser');
        //接收参数
        $page = $this->request->param('page',1);
        $size = $this->request->param('size',20);
        $page = ($page-1)*$size;
        $type = $this->request->param('type',1);
        $date_type = $this->request->param('date_type',1);
        $select_date = $this->request->param('select_date');
        if($date_type=='4' && (empty($select_date) || $select_date=='null ')){
            $this->error('请选择查询日期');
        }
        $select_date = json_decode(htmlspecialchars_decode($select_date),true);
        $time = $this->formart_type_date($date_type,$select_date);
        $daili_user_id = empty($user['daili_account_id'])?$user['user_id']:$user['daili_account_id'];
        $daili_user = Users::where('user_id',$daili_user_id)->find();
        if($daili_user['is_daili'] == 0){
            $this->error("您不是代理");
        }
        //代理城市
        $office['city_name'] = Region::getRegionName($daili_user['daili_city']);
        //获取当前收益
        $office['today_sy']= UserFinance::where("user_id=$daili_user_id and money_type=1 and is_jia =1 and msg_type in (401,604) and create_time>=$time[0] and create_time<$time[1]")->sum('money');
        $office['today_sy'] = round($office['today_sy'],2);
        //获取总收益
        $office['total_sy']= UserFinance::where("user_id=$daili_user_id and money_type=1 and is_jia =1 and msg_type in (401,604)")->sum('money');
        $office['total_sy'] = round($office['total_sy'],2);
        //获取列表
        if($type==1){
            $data['list'] = UserFinance::where("user_id=$daili_user_id and money_type=1 and is_jia =1 and msg_type in (401,604) and create_time>=$time[0] and create_time<$time[1]")->limit($page,$size)->order('create_time desc')->select();
        }else{
            $data['list'] = UserFinance::where("user_id=$daili_user_id and money_type=1 and is_jia =1 and msg_type in (401,604)")->limit($page,$size)->order('create_time desc')->select();
        }
        $data['office'] = $office;
        $this->success('加载成功',$data);
    }

    /**
     * 格式化查询时间
     * @param $type 类型
     * @param $select_date 选择的时间
     * @return array
     */
    public function formart_type_date($type,$select_date){
        if($type==1){//当天
            $data[0] = strtotime(date("Y-m-d"));
            $data[1] = $data[0]+24*60*60;
        }else if($type==2){ //当月
            $data[0] = strtotime(date("Y-m-01"));
            $data[1] = strtotime(date("Y-m-31"))+24*60*60;
        }else if($type==3){//当年
            $data[0] = strtotime(date("Y-01-01"));
            $data[1] = strtotime(date("Y-12-31"))+24*60*60;
        }else if($type==4){
            $data[0] = strtotime($select_date[0]);
            $data[1] = strtotime($select_date[1])+24*60*60;
        }else{
            $data[0] = 0;
            $data[1] = 99999999999;
        }
        return $data;
    }


    public function getcoupon(){
        $user = session('authuser');
        //接收参数
        $page = $this->request->param('page',1);
        $size = $this->request->param('size',20);
        $page = ($page-1)*$size;
        $type = $this->request->param('type',0);

        $where=array('user_id'=>$user['user_id'],'money_type'=>6);
        if($type==1){
            $where=array('user_id'=>$user['user_id'],'money_type'=>6,'is_jia'=>1);
        }
        if($type==2){
            $where=array('user_id'=>$user['user_id'],'money_type'=>6,'is_jia'=>2);
        }

        $coupon = UserFinance::where($where)->order('create_time desc')->limit($page,$size)->select();
        foreach ($coupon as $row){
            $row->money = str_format_two($row['money']);
        }
        $this->success('加载成功',$coupon);
    }

    public function getred(){
        $user = session('authuser');
        //接收参数
        $page = $this->request->param('page',1);
        $size = $this->request->param('size',20);
        $page = ($page-1)*$size;
        $type = $this->request->param('type',0);

        $where=array('user_id'=>$user['user_id'],'money_type'=>2);
        if($type==1){
            $where=array('user_id'=>$user['user_id'],'money_type'=>2,'is_jia'=>1);
        }
        if($type==2){
            $where=array('user_id'=>$user['user_id'],'money_type'=>2,'is_jia'=>2);
        }

        $coupon = UserFinance::where($where)->order('create_time desc')->limit($page,$size)->select();
        foreach ($coupon as $row){
            $row->money = str_format_two($row['money']);
        }
        $this->success('加载成功',$coupon);
    }
}